<template>
  <section class="profile">
    <h1 class="title">个人中心</h1>

    <div v-if="user">
      <div class="card">
        <div class="usercard">
          <div class="avatar">{{ initials(user.username) }}</div>
          <div>
            <div class="name">{{ user.username }}</div>
            <div v-if="user.isMember" class="member-status" :class="`member-${user.memberLevel}`">
              <span class="member-icon">💎</span>
              <span>{{ memberLevelName }}</span>
              <span class="expires">有效期至：{{ formatDate(user.memberExpires) }}</span>
            </div>
          </div>
        </div>
        <div class="ops">
          <router-link to="/member" class="member-btn">会员中心</router-link>
          <button class="logout" @click="onLogout">退出登录</button>
        </div>
      </div>

      <div class="card passcard">
        <h2 class="sub">修改密码</h2>
        <form class="form" @submit.prevent="onChangePass">
          <input v-model="oldPass" type="password" placeholder="旧密码" autocomplete="current-password" />
          <input v-model="newPass" type="password" placeholder="新密码" autocomplete="new-password" @input="checkPasswordStrength" />
          <div v-if="newPass" class="password-strength">
            <div class="strength-bars">
              <div 
                class="strength-bar"
                :class="{ 
                  'weak': passwordStrength >= 1,
                  'medium': passwordStrength >= 2,
                  'strong': passwordStrength >= 3
                }"
              ></div>
            </div>
            <p class="strength-text" :class="strengthClass">{{ strengthText }}</p>
          </div>
          <button type="submit" :disabled="!isPasswordValid">保存</button>
          <p v-if="msg" :class="ok ? 'ok' : 'err'">{{ msg }}</p>
        </form>
      </div>

      <div class="card comments">
        <h2 class="sub">我的评论</h2>
        <ul class="list">
          <li v-for="c in mine" :key="c.id" class="item">
            <div class="line">
              <span class="time">{{ fmt(c.time) }}</span>
              <button class="del" @click="remove(c)">删除</button>
            </div>
            <p class="content">{{ c.content }}</p>
          </li>
        </ul>
        <p v-if="!mine.length" class="empty">还没有评论</p>
      </div>

      <div class="card favorites">
        <div class="subline">
          <h2 class="sub">我的收藏</h2>
          <button class="clear" @click="clearFavs" :disabled="!favs.length">清空</button>
        </div>
        <ul class="media-list">
          <li v-for="v in favs" :key="v.id" class="media-item">
            <router-link :to="'/watch/' + v.id" class="media-link">
              <img :src="v.thumb || '/images/poster.svg'" alt="thumb" />
              <span class="mtitle">{{ v.title }}</span>
            </router-link>
          </li>
        </ul>
        <p v-if="!favs.length" class="empty">还没有收藏视频</p>
      </div>

      <div class="card history">
        <div class="subline">
          <h2 class="sub">观看历史</h2>
          <button class="clear" @click="clearHist" :disabled="!hist.length">清空</button>
        </div>
        <ul class="media-list">
          <li v-for="h in hist" :key="h.id + h.time" class="media-item">
            <router-link :to="'/watch/' + h.id" class="media-link">
              <img :src="h.thumb || '/images/poster.svg'" alt="thumb" />
              <span class="mtitle">{{ h.title }}</span>
              <span class="mtime">{{ fmt(h.time) }}</span>
            </router-link>
          </li>
        </ul>
        <p v-if="!hist.length" class="empty">还没有观看记录</p>
      </div>
    </div>
    
    <div v-else>
      <p class="empty">请先登录</p>
      <button class="login" @click="goLogin">去登录</button>
    </div>
  </section>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import comments from '@/data/comments'
import { getCurrentUser, logout, changePassword } from '@/utils/auth'
import { getFavorites, clearFavorites, getHistory, clearHistory } from '@/utils/userdata'

const router = useRouter()
const user = computed(() => getCurrentUser())
const mine = computed(() => comments.filter(c => c.user === user.value?.username).sort((a,b) => new Date(b.time) - new Date(a.time)))

// 会员等级名称
const memberLevelName = computed(() => {
  if (!user.value?.isMember) return ''
  const levels = {
    standard: '标准会员',
    premium: '高级会员'
  }
  return levels[user.value.memberLevel] || '会员'
})

// 格式化日期
function formatDate(dateString) {
  if (!dateString) return '未知'
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  })
}

const favs = ref([])
const hist = ref([])
function refreshLists() {
  if (!user.value) { favs.value = []; hist.value = []; return }
  favs.value = getFavorites(user.value.username)
  hist.value = getHistory(user.value.username)
}

const oldPass = ref('')
const newPass = ref('')
const msg = ref('')
const ok = ref(false)
const passwordStrength = ref(0)

// 检测密码强度
function checkPasswordStrength() {
  const pwd = newPass.value
  let strength = 0
  
  // 检查密码长度
  if (pwd.length >= 8) strength += 1
  
  // 检查是否包含数字和字母
  const hasNumber = /\d/.test(pwd)
  const hasLetter = /[a-zA-Z]/.test(pwd)
  const hasSymbol = /[^a-zA-Z0-9]/.test(pwd)
  
  if (hasNumber && hasLetter) strength += 1
  if (hasSymbol && hasNumber && hasLetter) strength += 1
  
  passwordStrength.value = strength
}

// 计算密码强度文本
const strengthText = computed(() => {
  if (!newPass.value) return ''
  if (newPass.value.length < 8) return '密码长度必须不少于8位'
  
  if (passwordStrength.value === 1) return '密码强度：弱（需要包含数字和字母）'
  if (passwordStrength.value === 2) return '密码强度：中等（建议添加特殊符号）'
  return '密码强度：强'
})

// 计算密码强度样式类
const strengthClass = computed(() => {
  if (!newPass.value) return ''
  if (passwordStrength.value === 1) return 'weak-text'
  if (passwordStrength.value === 2) return 'medium-text'
  return 'strong-text'
})

// 密码是否有效
const isPasswordValid = computed(() => {
  return newPass.value.length >= 8 && passwordStrength.value >= 2
})

function onLogout() { logout(); router.push('/') }
function onChangePass() {
  msg.value = ''; ok.value = false
  
  // 再次验证密码强度
  checkPasswordStrength()
  
  if (!isPasswordValid.value) {
    msg.value = '密码不符合要求，请设置包含数字和字母的密码，长度不少于8位'
    return
  }
  
  try {
    changePassword(oldPass.value, newPass.value)
    msg.value = '修改成功'; ok.value = true
    oldPass.value = ''; newPass.value = ''
  } catch (e) {
    msg.value = e?.message || '保存失败'
  }
}
function remove(c) {
  const i = comments.findIndex(x => x.id === c.id)
  if (i !== -1) comments.splice(i, 1)
}
function fmt(t) { const d = new Date(t); return d.toLocaleString() }
function initials(name) { return (name || '?').slice(0, 1).toUpperCase() }
function goLogin() { router.push('/login') }
function clearFavs() { if (!user.value) return; clearFavorites(user.value.username); refreshLists() }
function clearHist() { if (!user.value) return; clearHistory(user.value.username); refreshLists() }

function onChanged() { refreshLists() }
onMounted(() => {
  if (!user.value) router.push('/login')
  refreshLists()
  window.addEventListener('userdata-changed', onChanged)
})
onBeforeUnmount(() => {
  window.removeEventListener('userdata-changed', onChanged)
})
</script>

<style scoped>
.profile { max-width: 720px; margin: 0 auto; }
.title { margin: 12px 4px 12px; font-size: 24px; font-weight: 800; }
.card { background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius); padding: 12px; margin-bottom: 16px; box-shadow: var(--shadow-sm); }

/* 密码强度指示器样式 */
.password-strength {
  display: grid;
  gap: 6px;
  margin-bottom: 8px;
}

.strength-bars {
  height: 4px;
  background-color: #e5e7eb;
  border-radius: 2px;
  overflow: hidden;
}

.strength-bar {
  height: 100%;
  width: 0;
  transition: width 0.3s ease;
}

.strength-bar.weak {
  width: 33%;
  background-color: #d14343;
}

.strength-bar.medium {
  width: 66%;
  background-color: #f59e0b;
}

.strength-bar.strong {
  width: 100%;
  background-color: #10b981;
}

.strength-text {
  font-size: 14px;
  margin: 0;
}

.weak-text {
  color: #d14343;
}

.medium-text {
  color: #f59e0b;
}

.strong-text {
  color: #10b981;
}

button:disabled {
  background: #cccccc;
  cursor: not-allowed;
}
.usercard { display: grid; grid-template-columns: 60px 1fr; gap: 12px; align-items: center; }
.avatar { width: 60px; height: 60px; border-radius: 50%; background: #e6f7ff; color: #0077b8; display: inline-flex; align-items: center; justify-content: center; font-weight: 700; font-size: 24px; }
.name { font-weight: 700; font-size: 18px; }
.member-status {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-top: 4px;
  padding: 4px 8px;
  border-radius: 6px;
  font-size: 12px;
  font-weight: 600;
}

.member-status.member-standard {
  background: rgba(0, 161, 214, 0.1);
  color: #00a1d6;
}

.member-status.member-premium {
  background: rgba(139, 92, 246, 0.1);
  color: #8b5cf6;
}

.member-icon {
  font-size: 14px;
}

.expires {
  font-size: 11px;
  opacity: 0.8;
  font-weight: normal;
}

.ops {
  margin-top: 8px;
  display: flex;
  gap: 8px;
  align-items: center;
}

.member-btn {
  padding: 6px 12px;
  border-radius: 999px;
  border: none;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  text-decoration: none;
  font-size: 12px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s ease;
}

.member-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.logout {
  padding: 6px 12px;
  border-radius: 999px;
  border: 1px solid var(--border);
  background: #fff;
  color: #374151;
  cursor: pointer;
  transition: border-color 0.2s ease, transform 0.08s ease;
}

.logout:hover {
  border-color: #cfd2d6;
}

.logout:active {
  transform: scale(0.98);
}
.sub { margin: 0 0 8px; font-size: 18px; font-weight: 700; }
.form { display: flex; flex-direction: column; gap: 12px; }
.form input { padding: 10px 12px; border: 1px solid var(--border); border-radius: 10px; background: #fff; color: #374151; }
.form button { padding: 8px 14px; border-radius: 999px; background: linear-gradient(90deg, #00a1d6, #06b6d4); color: #fff; border: none; cursor: pointer; }
.ok { color: #137b13; }
.err { color: #d14343; }
.list { list-style: none; margin: 0; padding: 0; display: grid; gap: 10px; }
.item { padding: 8px 10px; border: 1px solid var(--border); border-radius: 10px; }
.line { display: flex; justify-content: space-between; align-items: center; }
.time { color: var(--muted); font-size: 12px; }
.del { padding: 4px 10px; border-radius: 999px; border: 1px solid var(--border); background: #fff; color: #374151; cursor: pointer; transition: border-color 0.2s ease, transform 0.08s ease; }
.del:hover { border-color: #cfd2d6; }
.del:active { transform: scale(0.98); }
.content { margin: 6px 0 0; white-space: pre-wrap; word-break: break-word; }
.empty { color: var(--muted); }
.login { padding: 8px 14px; border-radius: 999px; border: 1px solid var(--border); background: #fff; color: #374151; cursor: pointer; }
.subline { display: flex; justify-content: space-between; align-items: center; }
.clear { padding: 6px 10px; border-radius: 999px; border: 1px solid var(--border); background: #fff; color: #374151; cursor: pointer; transition: border-color 0.2s ease, transform 0.08s ease; }
.clear:hover { border-color: #cfd2d6; }
.clear:active { transform: scale(0.98); }
.clear:disabled { opacity: 0.5; cursor: not-allowed; }
.media-list { list-style: none; margin: 0; padding: 0; display: grid; grid-template-columns: 1fr; gap: 10px; }
.media-item { border: 1px solid var(--border); border-radius: 10px; padding: 8px; }
.media-link { display: grid; grid-template-columns: 120px 1fr; gap: 12px; align-items: center; text-decoration: none; color: inherit; }
.media-link img { width: 120px; height: 72px; object-fit: cover; border-radius: 8px; background: #f3f4f6; }
.mtitle { font-weight: 600; }
.mtime { color: var(--muted); font-size: 12px; }
</style>